#!/bin/bash

echo "🚀 启动A2A多智能体协商可视化系统"
echo "=================================="

# 检查uv命令
if ! command -v uv &> /dev/null; then
    echo "❌ 未找到uv，请先安装uv"
    echo "   安装命令: pip install uv"
    exit 1
fi

# 检查端口占用情况
check_port() {
    if lsof -Pi :$1 -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo "⚠️  端口 $1 已被占用"
        return 1
    else
        echo "✅ 端口 $1 可用"
        return 0
    fi
}

echo ""
echo "🔍 检查端口占用情况..."
check_port 7001
check_port 7003
check_port 8000
check_port 8080

# 启动MCP服务器 (如果未运行)
if ! lsof -i :7001 >/dev/null 2>&1; then
    echo ""
    echo "🔍 启动MCP服务器 (端口 7001)..."
    uv run python mcp_server.py &
    MCP_PID=$!
    echo "MCP服务器进程ID: $MCP_PID"
    sleep 3
fi

# 启动WeatherAgent (如果未运行)
if ! lsof -i :7003 >/dev/null 2>&1; then
    echo ""
    echo "🤖 启动WeatherAgent (端口 7003)..."
    uv run python intelligent_weather_agent.py &
    WEATHER_PID=$!
    echo "WeatherAgent进程ID: $WEATHER_PID"
    sleep 3
fi

# 启动Web后端 (如果未运行)
if ! lsof -i :8000 >/dev/null 2>&1; then
    echo ""
    echo "🌐 启动Web后端服务 (端口 8000)..."
    cd web_interface/backend
    uv run python web_backend.py &
    WEB_BACKEND_PID=$!
    echo "Web后端进程ID: $WEB_BACKEND_PID"
    cd ../..
    sleep 3
fi

# 启动Web前端服务 (如果未运行)
if ! lsof -i :8080 >/dev/null 2>&1; then
    echo ""
    echo "📄 启动Web前端服务 (端口 8080)..."
    cd web_interface/frontend
    uv run python -m http.server 8080 &
    WEB_FRONTEND_PID=$!
    echo "Web前端进程ID: $WEB_FRONTEND_PID"
    cd ../..
    sleep 2
fi

echo ""
echo "📊 服务状态检查..."
echo "  🔍 MCP服务器 (端口7001): $(lsof -i :7001 >/dev/null && echo '✅ 运行中' || echo '❌ 未运行')"
echo "  🤖 WeatherAgent (端口7003): $(lsof -i :7003 >/dev/null && echo '✅ 运行中' || echo '❌ 未运行')"
echo "  🌐 Web后端 (端口8000): $(lsof -i :8000 >/dev/null && echo '✅ 运行中' || echo '❌ 未运行')"
echo "  📄 前端服务 (端口8080): $(lsof -i :8080 >/dev/null && echo '✅ 运行中' || echo '❌ 未运行')"

echo ""
echo "🎯 访问地址:"
echo "  📱 可视化界面: http://localhost:8080"
echo "  📖 API文档: http://localhost:8000/docs"
echo "  🔍 健康检查: http://localhost:8000/health"

echo ""
echo "💡 使用说明:"
echo "  1. 在浏览器中打开 http://localhost:8080"
echo "  2. 在左侧输入您的旅行需求"
echo "  3. 点击'开始AI团队协商'按钮"
echo "  4. 实时观看Agent间的协商过程"
echo "  5. 查看详细的决策过程和最终结果"

echo ""
echo "🔧 管理命令:"
echo "  📋 查看协商日志: ./view_logs.sh"
echo "  🧠 分析决策过程: ./analyze_decisions.sh"
echo "  🛑 停止所有服务: fuser -k 7001/tcp 7003/tcp 8000/tcp 8080/tcp"

echo ""
echo "✨ 享受A2A多智能体协商的魅力！"

# 保持脚本运行，显示进程状态
echo ""
echo "🔄 系统正在运行... (按 Ctrl+C 停止所有服务)"
trap 'echo ""; echo "🛑 停止所有服务..."; fuser -k 7001/tcp 7003/tcp 8000/tcp 8080/tcp 2>/dev/null; exit 0' INT

# 定期检查服务状态
while true; do
    sleep 30
    echo ""
    echo "📊 服务状态更新 ($(date '+%H:%M:%S')):"
    echo "  🔍 MCP服务器: $(lsof -i :7001 >/dev/null && echo '✅' || echo '❌')"
    echo "  🤖 WeatherAgent: $(lsof -i :7003 >/dev/null && echo '✅' || echo '❌')"
    echo "  🌐 Web后端: $(lsof -i :8000 >/dev/null && echo '✅' || echo '❌')"
    echo "  📄 前端服务: $(lsof -i :8080 >/dev/null && echo '✅' || echo '❌')"
done
